package com.zmx.user.web;

import com.netflix.ribbon.proxy.annotation.Http;
import com.zmx.common.common.utils.HttpUtil;
import com.zmx.common.common.web.rest.ResponseResult;
import com.zmx.user.dto.MemberDto;
import com.zmx.user.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaomingxing
 * @Title: WxController
 * @ProjectName accurate_sale
 * @Description: TODO
 * @date 2019/8/2010:59
 */
@Slf4j
@Api(value = "微信接口控制器")
@RestController
@RequestMapping("wx")
public class WxController {

    //微信 appid
    @Value("${weixin.appId}")
    private String appId;
    //微信 appSecret
    @Value("${weixin.appSecret}")
    private String appSecret;
    //获取openid的url地址
    @Value("${weixin.openid_url}")
    private String openid_url;
    //获取access_token的url地址
    @Value("${weixin.access_token_url}")
    private String access_token_url;
    //获取jsapi_ticket的url地址
    @Value("${weixin.jsapi_ticket_url}")
    private String jsapi_ticket_url;


    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "根据code获取微信openId", tags = "根据code获取微信openId")
    @GetMapping(value = "getWxOpenId")
    public ResponseResult getWxOpenId(@RequestParam("code") String code) {
        log.info("begin to getWxOpenId code: {}" + code);
        try {
            Map params = new HashMap();
            params.put("secret", this.appSecret);
            params.put("appid", this.appId);
            params.put("grant_type", "authorization_code");
            params.put("code", code);
            String result = HttpUtil.get(this.openid_url, params);

            JSONObject jsonObject = JSONObject.fromObject(result);
            String openid = jsonObject != null && jsonObject.get("openid") != null ? jsonObject.get("openid").toString() : "";
            log.info("getOpenId 得到的openid为: {}", openid);

            return ResponseResult.success(openid);
        } catch (Exception e) {
            log.error("获取openId失败!", e);
            return ResponseResult.fail("获取openId失败");
        }
    }

    @ApiOperation(value = "获取accessToken", tags = "获取accessToken")
    @GetMapping(value = "getAccessToken")
    private ResponseResult getAccessToken(@RequestParam("openId") String openId) {
        log.info("begin to getAccessToken openId=>" + openId);
        MemberDto memberDto = memberService.findByOpenid(openId);
        if (memberDto == null || memberDto.getIsVaild() != 1) {
            log.info("该用户不存在,无法获取accessToken ");
            return ResponseResult.fail("该用户不存在,无法获取accessToken");
        }

        try {
            Map params = new HashMap(3);
            params.put("secret", this.appSecret);
            params.put("appid", this.appId);
            params.put("grant_type", "client_credential");
            String result = HttpUtil.get(this.access_token_url, params);
            log.info("getAccessToken.result: {}", result);

            JSONObject jsonObject = JSONObject.fromObject(result);
            String access_token = jsonObject.get("access_token") != null ? jsonObject.get("access_token").toString() : "";
            String expires_in = jsonObject.get("expires_in").toString();
            log.info("getAccessToken.access_token: {}, expires_in: {}", access_token, expires_in);

            return ResponseResult.success(access_token);
        } catch (Exception e) {
            log.error("获取accessToken出错啦!", e);
            return ResponseResult.fail("获取accessToken失败");
        }
    }

    /**
     * 获取jsapiTicket
     * @return
     */
   /* private String getJsapiTicket(){
        String access_token = getAccessToken();//先获取access_token
        Map params = new HashMap();
        params.put("access_token", access_token);
        params.put("type", "jsapi");
        String result = HttpGetUtil.httpRequestToString(this.jsapi_ticket_url, params);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String ticket = jsonObject.get("ticket").toString();
        String expires_in = jsonObject.get("expires_in").toString();
        logger.info("getJsapiTicket.ticket:" + ticket + " expires_in:" + expires_in);
        return ticket;
    }*/

    @GetMapping("token")
    public void wxToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //此处的token就是url下面自定义填写用于验证服务器的token
        String token = "13050103501zmx";
        String echostr = request.getParameter("echostr");
        PrintWriter pw = response.getWriter();
        //将微信服务器发送过来的随机字符串返回给微信服务器
        pw.append(echostr);
        pw.flush();
        pw.close();
    }
}
